import { Dispatch, State } from './types';
import navigator from '../../util/navigator';
import { Data } from '../../api/course/getCommodityDetail';
import { CourseApi } from '../../api';

let dispatch: Dispatch;
let state: State;

let reload = (): void => {};

export default (d: Dispatch, s: State): void => {
  dispatch = d;
  state = s;
};

export const getReload = (): void => {
  reload();
};

export const setProductId = (value: number): void => {
  dispatch({ type: 'SET_PRODUCT_ID', value });
};

export const setProductInfo = (value: any): void => {
  dispatch({ type: 'SET_PRODUCT_INFO', value });
};

export const setRealPrice = (value: any): void => {
  dispatch({ type: 'SET_REAL_PRICE', value });
};

export const setSelectedIds = (value: number[]): void => {
  dispatch({ type: 'SET_SELECTED_IDS', value });
};

export const setIsShowSkus = (value: boolean): void => {
  dispatch({ type: 'SET_IS_SHOW_SKUS', value });
};

export const setSpuInfo = (value: Data): void => {
  dispatch({ type: 'SET_SPU_INFO', value });
};

export const fetchFailed = (): void => {
  dispatch({ type: 'FETCH_FAILED' });
};

export const getProductInfo = async (commodityId: number): Promise<void> => {
  reload = (): Promise<void> => getProductInfo(commodityId);
  const res = await CourseApi.getCommodityDetail({ commodityId });
  const { code, data } = res;
  if (code !== 0) return;
  setSpuInfo({ ...data, commodityId });
};

export const goPay = (): void => {
  const { spuInfo } = state;
  navigator.push('Order', { spuList: [spuInfo] });
};

export const onPressContactTeacher = (): void => {
  navigator.push('Contact');
};
